package com.mark.service.impl;

import com.mark.dto.OrderDTO;
import com.mark.enums.ResultEnum;
import com.mark.exception.SellException;
import com.mark.service.IBuyerService;
import com.mark.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by Choisaaaa on 2018/6/22.
 */

@Service
@Slf4j
public class IBuyerServiceImpl implements IBuyerService {

    @Autowired
    private IOrderService iOrderService;

    @Override
    public OrderDTO findOrderOne(String openid, String orderId) {
        return this.checkOrderOwner(openid, orderId);
    }

    @Override
    public OrderDTO cancelOrder(String openid, String orderId) {
        OrderDTO orderDTO =  checkOrderOwner(openid, orderId);
        if (null == orderDTO) {
            log.error("【取消订单】查不到改订单, orderId={}", orderId);
            throw new SellException(ResultEnum.ORDER_NOT_EXIST);
        }
        return iOrderService.cancel(orderDTO);
    }

    private OrderDTO checkOrderOwner(String openid, String orderId) {
        OrderDTO orderDTO = iOrderService.findOne(orderId);
        if (null == orderDTO) {
            return null;
        }
        //判断是否为自己的订单
        if (!orderDTO.getBuyerOpenid().equals(openid)){
            log.error("【查询订单】订单的openid不一致. openid={}, orderDTO={}", openid, orderDTO);
            throw new SellException(ResultEnum.ORDER_OWNER_ERROR);
        }
        return orderDTO;
    }
}
